import sys
import json
import os
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QLabel, QLineEdit, QListWidget, 
                            QPushButton, QMessageBox, QFrame)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QColor

class TodoApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.DATA_FILE = os.path.join(os.path.expanduser('~'), 'todo.json')
        self.BASE_DIR = self._get_base_dir()
        # self.IMAGE_PATH = self.get_resource_path('image.png')
        self.COLORS = {
            'bg': '#f0f2f5',
            'button_add': '#ffd591',
            'button_toggle': '#b7eb8f',
            'button_delete': '#ffa39e',
            'frame_bg': '#ffffff',
            'text': '#000000'
        }
        
        self.tasks = self.load_data()
        # 添加基准尺寸和字体大小
        self.base_width = 768
        self.base_font_sizes = {
            'title': 28,
            'label': 18,
            'input': 16,
            'button': 16,
            'list': 30
        }
        
        self.init_ui()
        
    def _get_base_dir(self):
        """获取应用程序的基础路径"""
        if getattr(sys, 'frozen', False):
            # 如果是打包后的应用程序
            return os.path.dirname(sys.executable)
        # 如果开发环境
        return os.path.dirname(os.path.abspath(__file__))
        
    def init_ui(self):
        self.setWindowTitle('ToDo List')
        # 删除固定尺寸的限制
        # self.setFixedSize(768, 1024)
        
        # 设置最小窗口尺寸，确保界面元素不会挤在一起
        self.setMinimumSize(500, 700)
        
        # 设置默认窗口尺寸
        self.resize(768, 1024)
        
        self.setStyleSheet(f"background-color: {self.COLORS['bg']};")

        # 主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        # 主布局
        layout = QVBoxLayout(main_widget)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)
        
        # 创建主框架
        main_frame = QFrame()
        main_frame.setStyleSheet(f"""
            QFrame {{
                background-color: {self.COLORS['frame_bg']};
                border: 1px solid #e0e0e0;
                border-radius: 8px;
            }}
        """)
        frame_layout = QVBoxLayout(main_frame)
        frame_layout.setSpacing(10)
        frame_layout.setContentsMargins(15, 15, 15, 15)
        
        # 标题
        title = QLabel('ToDo-List')
        title.setObjectName('title')
        title.setFont(QFont('Microsoft YaHei UI', 28, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title.setStyleSheet(f"""
            QLabel {{
                color: {self.COLORS['text']};
                border: none;
                background: transparent;
            }}
        """)
        frame_layout.addWidget(title)
        
        # 添加分隔空间
        frame_layout.addSpacing(20)
        
        # 任务输入区域
        task_label = QLabel('任务内容:')
        task_label.setFont(QFont('Microsoft YaHei UI', 18))
        task_label.setStyleSheet(f"""
            QLabel {{
                color: {self.COLORS['text']};
                border: none;
                background: transparent;
            }}
        """)
        self.task_entry = QLineEdit()
        self.task_entry.setFont(QFont('Microsoft YaHei UI', 16))
        self.task_entry.setStyleSheet(f"""
            QLineEdit {{
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                color: {self.COLORS['text']};
            }}
        """)
        
        category_label = QLabel('分类:')
        category_label.setFont(QFont('Microsoft YaHei UI', 18))
        category_label.setStyleSheet(f"""
            QLabel {{
                color: {self.COLORS['text']};
                border: none;
                background: transparent;
            }}
        """)
        self.category_entry = QLineEdit()
        self.category_entry.setFont(QFont('Microsoft YaHei UI', 16))
        self.category_entry.setStyleSheet(f"""
            QLineEdit {{
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                color: {self.COLORS['text']};
            }}
        """)
        
        frame_layout.addWidget(task_label)
        frame_layout.addWidget(self.task_entry)
        frame_layout.addWidget(category_label)
        frame_layout.addWidget(self.category_entry)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.setSpacing(15)
        self.add_button = self.create_button("添加任务", self.add_task, self.COLORS['button_add'])
        self.toggle_button = self.create_button("切换状态", self.toggle_task, self.COLORS['button_toggle'])
        self.delete_button = self.create_button("删除任务", self.delete_task, self.COLORS['button_delete'])
        
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.toggle_button)
        button_layout.addWidget(self.delete_button)
        frame_layout.addLayout(button_layout)
        
        # 任务列表
        self.tasks_list = QListWidget()
        self.tasks_list.setFont(QFont('Microsoft YaHei UI', 30))
        self.tasks_list.setMinimumHeight(500)
        self.tasks_list.setStyleSheet(f"""
            QListWidget {{
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 5px;
                color: {self.COLORS['text']};
            }}
            QListWidget::item {{
                padding: 8px;
                margin: 2px 0;
                background-color: transparent;
            }}
            QListWidget::item:selected {{
                background-color: rgba(230, 247, 255, 180);
                color: {self.COLORS['text']};
            }}
        """)
        frame_layout.addWidget(self.tasks_list)
        
        layout.addWidget(main_frame)
        self.update_listbox()
        
    def create_button(self, text, slot, color):
        button = QPushButton(text)
        button.setFont(QFont('Microsoft YaHei UI', 16))
        button.setStyleSheet(f"""
            QPushButton {{
                background-color: {color};
                border: 1px solid #ddd;
                padding: 12px 24px;
                border-radius: 4px;
                color: {self.COLORS['text']};
                font-weight: bold;
            }}
            QPushButton:hover {{
                background-color: {self.darken_color(color)};
            }}
        """)
        button.clicked.connect(slot)
        return button

    def load_data(self):
        """加载数据文件"""
        try:
            if os.path.exists(self.DATA_FILE):
                with open(self.DATA_FILE, 'r', encoding='utf-8') as file:
                    content = file.read().strip()
                    return json.loads(content) if content else []
        except Exception as e:
            # 添加错误处理
            QMessageBox.warning(self, "错误", f"加载数据失败: {str(e)}")
            return []
        return []

    def save_data(self):
        """保存数据到文件"""
        try:
            with open(self.DATA_FILE, 'w', encoding='utf-8') as file:
                json.dump(self.tasks, file, ensure_ascii=False, indent=4)
        except Exception as e:
            # 添加错误处理
            QMessageBox.warning(self, "错误", f"保存数据失败: {str(e)}")

    def update_listbox(self):
        self.tasks_list.clear()
        for task in self.tasks:
            status = "✓" if task.get('completed', False) else "□"
            self.tasks_list.addItem(f"{status} {task['task']} [{task['category']}]")

    def add_task(self):
        try:
            task = self.task_entry.text().strip()
            category = self.category_entry.text().strip()
            if task and category:
                self.tasks.append({
                    'task': task,
                    'category': category,
                    'completed': False
                })
                self.save_data()
                self.update_listbox()
                self.task_entry.clear()
                self.category_entry.clear()
            else:
                QMessageBox.warning(self, "提示", "请填写任务内容和分类")
        except Exception as e:
            QMessageBox.warning(self, "错误", f"添加任务失败: {str(e)}")

    def toggle_task(self):
        current_row = self.tasks_list.currentRow()
        if current_row >= 0:
            self.tasks[current_row]['completed'] = not self.tasks[current_row].get('completed', False)
            self.save_data()
            self.update_listbox()

    def delete_task(self):
        current_row = self.tasks_list.currentRow()
        if current_row >= 0:
            del self.tasks[current_row]
            self.save_data()
            self.update_listbox()

    @staticmethod
    def darken_color(color):
        # 将颜色变暗的辅助方法
        if color.startswith('#'):
            r = int(color[1:3], 16)
            g = int(color[3:5], 16)
            b = int(color[5:7], 16)
            factor = 0.8
            return f'#{int(r*factor):02x}{int(g*factor):02x}{int(b*factor):02x}'
        return color

    def get_resource_path(self, relative_path):
        """获取资源文件的绝对路径"""
        if getattr(sys, 'frozen', False):
            # 如果是打包后的可执行文件
            base_path = sys._MEIPASS
        else:
            # 如果是开发环境
            base_path = os.path.dirname(os.path.abspath(__file__))
        return os.path.join(base_path, relative_path)

    def resizeEvent(self, event):
        """处理窗口大小改变事件"""
        super().resizeEvent(event)
        self.adjust_font_sizes()
        
    def adjust_font_sizes(self):
        """根据窗口大小调整字体大小"""
        # 计算缩放比例
        width_ratio = self.width() / self.base_width
        scale_factor = max(0.7, min(width_ratio, 1.3))  # 限制缩放范围在0.7-1.3之间
        
        # 更新标题字体
        title_font = QFont('Microsoft YaHei UI', int(self.base_font_sizes['title'] * scale_factor), QFont.Weight.Bold)
        self.findChild(QLabel, 'title').setFont(title_font)
        
        # 更新标签字体
        label_font = QFont('Microsoft YaHei UI', int(self.base_font_sizes['label'] * scale_factor))
        for label in self.findChildren(QLabel):
            if label.objectName() != 'title':
                label.setFont(label_font)
        
        # 更新输入框字体
        input_font = QFont('Microsoft YaHei UI', int(self.base_font_sizes['input'] * scale_factor))
        self.task_entry.setFont(input_font)
        self.category_entry.setFont(input_font)
        
        # 更新按钮字体
        button_font = QFont('Microsoft YaHei UI', int(self.base_font_sizes['button'] * scale_factor))
        for button in self.findChildren(QPushButton):
            button.setFont(button_font)
        
        # 更新列表字体
        list_font = QFont('Microsoft YaHei UI', int(self.base_font_sizes['list'] * scale_factor))
        self.tasks_list.setFont(list_font)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = TodoApp()
    window.show()
    sys.exit(app.exec()) 